package com.kycxika.app.activity.pic;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.kycxika.app.R;
import com.kycxika.app.activity.base.BaseActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.kycxika.app.KycXikaApplication.context;

public class UserHeadActivity extends BaseActivity {


    private int startPos;
    private ArrayList<String> imgUrls;
    private ImageSize imageSize;
    private boolean showEdit;
    private List<View> guideViewList = new ArrayList<View>();
    public static final String INTENT_IMGURLS = "imgurls";
    public static final String INTENT_POSITION = "position";
    public static final String INTENT_IMAGESIZE = "imagesize";
    private ViewPager viewPager;
    private LinearLayout guideGroup;
    private ImageAdapter mAdapter;
    private View mTop;


    public static void startUserHeadActivity(Context context, List<String> imgUrls, int position, ImageSize imageSize, boolean showEdit) {
        Intent intent = new Intent(context, UserHeadActivity.class);
        intent.putStringArrayListExtra(INTENT_IMGURLS, new ArrayList<String>(imgUrls));
        intent.putExtra(INTENT_POSITION, position);
        intent.putExtra(INTENT_IMAGESIZE, imageSize);
        intent.putExtra("showEdit", showEdit);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        mTop = findViewById(R.id.top);
        setTop(mTop);
        getTitle("头像");
        getVisibility(true, this);
        rightVisibility("编辑图片", -1);

        viewPager = (ViewPager) findViewById(R.id.pager);
        guideGroup = (LinearLayout) findViewById(R.id.guideGroup);
    }

    @Override
    public void rightonClick() {
        choosePictrue();
    }

    @Override
    public void leftBlack() {
        startActivity(new Intent(this,SelfInfoActivity.class));
        this.finish();
    }

    @Override
    protected void initData() {
        getIntentData();
        mAdapter = new ImageAdapter(this);
        mAdapter.setDatas(imgUrls);
        mAdapter.setImageSize(imageSize);
        viewPager.setAdapter(mAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < guideViewList.size(); i++) {
                    guideViewList.get(i).setSelected(i == position ? true : false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setCurrentItem(startPos);

    }

    @Override
    protected void initListener() {

    }

    @Override
    public int getLayout() {
        return R.layout.activity_user_head;
    }

    private void choosePictrue() {
        Intent intent = new Intent(context, PhotoPickerActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean(PhotoPickerActivity.IS_MULTI_SELECT, false);
        bundle.putString(PhotoPickerActivity.SELECT_RESULTS, null);
        intent.putExtras(bundle);
        startActivityForResult(intent, 1001);
    }


    private void getIntentData() {
        startPos = getIntent().getIntExtra(INTENT_POSITION, 0);
        imgUrls = getIntent().getStringArrayListExtra(INTENT_IMGURLS);
        imageSize = (ImageSize) getIntent().getSerializableExtra(INTENT_IMAGESIZE);
        showEdit = getIntent().getBooleanExtra("showEdit", false);
    }

    private void addGuideView(LinearLayout guideGroup, int startPos, ArrayList<String> imgUrls) {
        if (imgUrls != null && imgUrls.size() > 0) {
            guideViewList.clear();
            for (int i = 0; i < imgUrls.size(); i++) {
                View view = new View(this);
                view.setBackgroundResource(R.drawable.selector_guide_bg);
                view.setSelected(i == startPos ? true : false);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.gudieview_width), getResources().getDimensionPixelSize(R.dimen.gudieview_heigh));
                layoutParams.setMargins(10, 0, 0, 0);
                guideGroup.addView(view, layoutParams);
                guideViewList.add(view);
            }
        }
    }

    private static class ImageAdapter extends PagerAdapter {

        private List<String> mdatas = new ArrayList<String>();
        private LayoutInflater inflater;
        private Context context;
        private ImageSize imageSize;
        private ImageView smallImageView = null;

        public void setDatas(List<String> datas) {
            if (datas != null) {
               // this.datas = datas;
                mdatas.clear();
                mdatas.addAll(datas);
            }
            notifyDataSetChanged();
        }

        public void setImageSize(ImageSize imageSize) {
            this.imageSize = imageSize;
        }

        public ImageAdapter(Context context) {
            this.context = context;
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            if (mdatas == null)
                return 0;
            return mdatas.size();
        }


        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = inflater.inflate(R.layout.item_pager_image, container, false);
            if (view != null) {
                final ImageView imageView = (ImageView) view.findViewById(R.id.imagepraent);

                if (imageSize != null) {
                    //预览imageView
                    smallImageView = new ImageView(context);
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(imageSize.getWidth(), imageSize.getHeight());
                    layoutParams.gravity = Gravity.CENTER;
                    smallImageView.setLayoutParams(layoutParams);
                    smallImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    ((FrameLayout) view).addView(smallImageView);
                }

                //loading
                final ProgressBar loading = new ProgressBar(context);
                FrameLayout.LayoutParams loadingLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                loadingLayoutParams.gravity = Gravity.CENTER;
                loading.setLayoutParams(loadingLayoutParams);
                ((FrameLayout) view).addView(loading);

                final String imgurl = mdatas.get(position);
                if (TextUtils.isEmpty(imgurl)) {
                    smallImageView.setImageResource(R.drawable.ce_02);
                } else {
                    Glide.with(context)
                            .load(imgurl)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存多个尺寸
                            .thumbnail(0.1f)//先显示缩略图  缩略图为原图的1/10
                            .error(R.drawable.ce_01)
                            .into(new GlideDrawableImageViewTarget(imageView) {
                                @Override
                                public void onLoadStarted(Drawable placeholder) {
                                    super.onLoadStarted(placeholder);
                               /* if(smallImageView!=null){
                                    smallImageView.setVisibility(ContractView.VISIBLE);
                                    Glide.with(context).load(imgurl).into(smallImageView);
                                }*/
                                    loading.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                    super.onLoadFailed(e, errorDrawable);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(ContractView.GONE);
                                }*/
                                    loading.setVisibility(View.GONE);
                                }

                                @Override
                                public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                                    super.onResourceReady(resource, animation);
                                    loading.setVisibility(View.GONE);
                                /*if(smallImageView!=null){
                                    smallImageView.setVisibility(ContractView.GONE);
                                }*/
                                }
                            });
                }

                container.addView(view, 0);
            }
            return view;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }
    }

    public static class ImageSize implements Serializable {

        private int width;
        private int height;

        public ImageSize(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getHeight() {
            return height;
        }

        public void setHeight(int height) {
            this.height = height;
        }

        public int getWidth() {
            return width;
        }

        public void setWidth(int width) {
            this.width = width;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            String resultPhotoUri = data.getStringExtra(PhotoPickerActivity.SELECT_RESULTS);
            if (resultPhotoUri == null) {
                return;
            }
            data.setClass(context, PicCutoutActivity.class);
            /*List<String> mlist = new ArrayList<>();
            mlist.add(resultPhotoUri);
            mAdapter.setDatas(mlist);*/
            startActivityForResult(data, 1002);
        }else if (requestCode == 1002 && resultCode == RESULT_OK) {
            String resultPhotoUri = data.getStringExtra(PhotoPickerActivity.SELECT_RESULTS);
            if (resultPhotoUri == null) {
                return;
            }
            //data.setClass(context, PicCutoutActivity.class);
            List<String> mlist = new ArrayList<>();
            mlist.add(resultPhotoUri);
            mAdapter.setDatas(mlist);
            //startActivityForResult(data, 1002);
        }
    }

}
